#pragma once

#include <iostream>
#include <time.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstdlib>

// 日志文件系统
// [日志等级][时间][信息][哪一个文件][哪一行]

#include <iostream>
#include <string>

#define SIZE 1024

// 日志文件打印位置
#define Screen 1
#define Onefile 2
#define Classfile 3

// 日志等级
enum
{
    Info,
    Debug,
    Warning,
    Error,
    Fatal
};

// 日志文件名称
static const std::string LogFile = "log.txt";

class Log
{
private:
    int PrintMethod;
    std::string path;

public:
    Log()
    {
        PrintMethod = Screen;
        path = "./log/";
    }
    ~Log()
    {
    }

private:
    // 日志等级转化为字符串
    std::string LevelToString(int level)
    {
        switch (level)
        {
        case Info:
            return "Info";
        case Debug:
            return "Debug";
        case Warning:
            return "Warning";
        case Error:
            return "Error";
        case Fatal:
            return "Fatal";
        default:
            return "None";
        }
    }
    // 打印日志的位置
    void PringLog(int level, const std::string &logtxt)
    {
        switch (PrintMethod)
        {
        case Screen:
            std::cout << logtxt << std::endl;
            break;
        case Onefile:
            PrintOneFile(LogFile, logtxt);
            break;
        case Classfile:
            PrintClassFile(level, logtxt);
            break;
        default:
            break;
        }
    }
    // 打印到一个文件中
    void PrintOneFile(const std::string &logname, const std::string &logtxt)
    {
        std::string _logname = path + logname;
        int fd = open(_logname.c_str(), O_CREAT | O_APPEND | O_WRONLY, 0666);
        if(fd < 0) return;
        write(fd, logtxt.c_str(), logtxt.size());
        close(fd);
    }
    // 根据日志等级打印到多个文件中
    void PrintClassFile(int level, const std::string &logtxt)
    {
        std::string filename = LogFile;
        filename += ".";
        filename += LevelToString(level);
        PrintOneFile(filename, logtxt);
    }

public:
    // 打印形式 建立
    void operator()(int level, const char *format, ...)
    {
        time_t t = time(nullptr);
        struct tm *ctime = localtime(&t);
        char leftbuffer[SIZE];
        snprintf(leftbuffer, sizeof(leftbuffer), "[%s][%d-%d-%d %d:%d:%d]",
                 LevelToString(level).c_str(), ctime->tm_year + 1900,
                 ctime->tm_mon + 1, ctime->tm_mday, ctime->tm_hour,
                 ctime->tm_min, ctime->tm_sec);

        va_list s;
        va_start(s, format);
        char rightbuffer[SIZE];
        vsnprintf(rightbuffer, sizeof(rightbuffer), format, s);
        va_end(s);

        // 格式: 默认部分 + 自定义部分
        char logtxt[SIZE * 2 + 10];
        snprintf(logtxt, sizeof(logtxt), "%s %s %s %d", leftbuffer, rightbuffer, __FILE__, __LINE__);

        // 打印日志的位置
        PringLog(level, logtxt);
    }
};

Log lg;